﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading;
using Cartoon.Common;

namespace Cartoon.Logic
{
    public class CartoonViewerService : ICartoonService
    {

        public CartoonViewerService()
        {
            this.DataReaded = 0;
        }

        protected long fileSize;
        protected long fileData;
        public long DataReaded;
        public double Progress
        {
            get
            {
                if (fileSize == 0) return 0;
                return (double)fileData / fileSize;
            }
        }
        protected int CacheLen = 1024 * 200; 

        #region ICartoonService 成员

        /// <summary>
        /// 获取url地址图片,大多数网站的图片都设置的防盗链
        /// 但指定相应的域名仿冒成是当前网站去读取图片数据
        /// 就轻松防盗链的法眼
        /// </summary>
        /// <param name="imgUrl">http图片地址</param>
        /// <param name="domain">referer 域名</param>
        /// <param name="savePath">保存路径</param>
        /// <returns></returns>
        public bool SaveImage(string imgUrl, string domain, string savePath)
        {   
            DownloadFile(imgUrl, domain, savePath); 
            return true; 
        }

        #endregion

        public void DownloadFile(string imgUrl, string domain, string savePath)
        { 
            long currentPos = 0;
            FileStream fs = null; 
            FileInfo f_info = new FileInfo(savePath);

            try
            {

                if (f_info.Exists == true)
                {
                    return;
                }

                string savePath_continue = savePath + ".td";

                FileInfo f_info_continue = new FileInfo(savePath_continue);
                if (f_info_continue.Exists == true)
                {

                    fs = f_info_continue.OpenWrite();
                    currentPos = f_info_continue.Length;
                    fileData = currentPos;
                    fs.Seek(currentPos, SeekOrigin.Current);
                }
                else
                {
                    fileData = 0;
                    fs = f_info_continue.Open(FileMode.OpenOrCreate);
                }  

                string url = imgUrl;

                HttpWebRequest request = null;
                WebResponse response = null; 
               
                request = (HttpWebRequest)WebRequest.Create(url); 
                //设置请求域名
                request.Referer = domain;
                request.Timeout = 1000 * 60 * 3;//3分钟
                request.AddRange((int)currentPos);
                 

                bool isWrong = false;
                string wrongMsg = "";
                try
                {
                    using (response = request.GetResponse())
                    {
                        using (Stream stm = response.GetResponseStream())
                        {
                            this.fileSize = response.ContentLength;
                            using (BinaryReader brd = new BinaryReader(stm))
                            { 
                                byte[] data = new byte[CacheLen];
                                int readlen = 0;
                                while ((readlen = brd.Read(data, 0, data.Length)) > 0)
                                {
                                    this.DataReaded += readlen;
                                    fs.Write(data, 0, readlen); 
                                    data = new byte[CacheLen];
                                }
                            }
                        }
                    }
                    fs.Close();
                }
                catch (ProtocolViolationException ex) { isWrong = true; wrongMsg = ex.Message; }
                catch (NotSupportedException ex) { isWrong = true; wrongMsg = ex.Message; }
                catch (WebException ex)
                {
                    isWrong = true;
                    wrongMsg = ex.Message;
                } 

                if (isWrong == true)
                {
                    Log.debug("下载文件出错：" + wrongMsg);
                    throw new Exception("下载文件出错：" + wrongMsg);
                }  

                File.Move(savePath_continue, savePath);
            }
            catch (Exception ex)
            {
                Log.debug("下载图片出错：" + ex.Message);
                throw new Exception("下载图片出错：" + ex.Message);
            }
            finally
            {
                if (fs != null)
                {
                    try
                    {
                        fs.Close();
                    }
                    catch { }
                }  
            }
        } 
        
    }
}
